﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using System.Xml;
using System.DirectoryServices;
using System.Reflection;
using System.Diagnostics;

namespace YouDaoNotesCodes
{
    public class PubCommon
    {
        #region 日志
        public static void WriteLog(string txt,string getMethod)
        {
            MethodBase method = new StackTrace(true).GetFrame(1).GetMethod();
            string fullName = method.DeclaringType.FullName;
            string name = method.Name;
            Console.WriteLine(fullName);
            Console.WriteLine(name);

            string strFilePath = string.Format("E:\\GSLog\\{0}\\",getMethod);
            if (!Directory.Exists(strFilePath))
                System.IO.Directory.CreateDirectory(strFilePath);

            string curDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            strFilePath += DateTime.Now.ToString("yyyy-MM-dd") + "_logfile.log";

            //System.IO.FileStream fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Append);
            System.IO.FileStream fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Append, FileAccess.Write, FileShare.ReadWrite);//文件的读写锁
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
            try
            {
                sw.WriteLine(String.Format("{0}  ↓↓↓", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")));
                sw.WriteLine(txt);
            }
            finally
            {
                sw.Close();
                fs.Close();
            }
        }
        #endregion

        /// <summary>
        /// 是否认证通过
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>true or false</returns>
        public static bool BeCertified(string username, string password)
        {
            try
            {
                string domain = GetConfigValue("DOMAIN");//10.16.43.109
                string path = String.Format("LDAP://{0}", domain);//LDAP://10.16.43.109
                DirectoryEntry user = new DirectoryEntry(path, username, password, AuthenticationTypes.Secure);
                user.RefreshCache();//当用户名或密码不正确的时候，此方法会抛出异常
            }
            catch
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取各配置的值
        /// </summary>
        public static string GetConfigValue(string keys)//获取key值，POTAL、USERCODE、PASSWORD
        {
            string confValue = string.Empty;
            //System.Reflection.Assembly.GetExecutingAssembly().Location + 
            string configfile = GetInterfacePhysicalPath();
            Dictionary<string, string> sectionNode = _getAppSettings();

            if (sectionNode.ContainsKey(keys))
            {
                confValue = sectionNode[keys];
            }
            return confValue;
        }

        /// <summary>
        /// 获取配置文件的物理路径
        /// </summary>
        /// <returns>返回配置文件的物理路径</returns>
        public static string GetInterfacePhysicalPath()
        {
            //string filePath = HttpContext.Current.Request.PhysicalApplicationPath;

            //string str1 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;//可获得当前执行的exe的文件名。 
            //string str2 = Environment.CurrentDirectory;//获取和设置当前目录（即该进程从中启动的目录）的完全限定路径。(备注:按照定义，如果该进程在本地或网络驱动器的根目录中启动，则此属性的值为驱动器名称后跟一个尾部反斜杠（如“C:\”）。如果该进程在子目录中启动，则此属性的值为不带尾部反斜杠的驱动器和子目录路径[如“C:\mySubDirectory”])。 
            //string str3 = Directory.GetCurrentDirectory(); //获取应用程序的当前工作目录。 
            //string str4 = AppDomain.CurrentDomain.BaseDirectory;//获取基目录，它由程序集冲突解决程序用来探测程序集。             
            //string str7 = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//获取或设置包含该应用程序的目录的名称。
            string filePath = String.Empty;
            try
            {
                filePath = HttpContext.Current.Request.PhysicalApplicationPath;
            }
            catch
            {
                filePath = Environment.CurrentDirectory;
            }

            int n = filePath.IndexOf("bscw_local");
            filePath = filePath.Substring(0, n) + "bscw_local\\JTGL" + "\\JTGL.config";
            return filePath;
        }

        /// <summary>
        /// 返回appsetting的列表
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> _getAppSettings()
        {
            XmlDocument xmlDoc = new XmlDocument();
            string configfile = GetInterfacePhysicalPath();
            xmlDoc.Load(configfile);
            XmlNode xmlNode = xmlDoc.SelectSingleNode("configuration/appSettings");
            Dictionary<string, string> sectionNode = new Dictionary<string, string>();
            foreach (XmlNode l in xmlNode.ChildNodes)
            {
                if (l.Name.ToLower() == "add")
                {
                    string name = l.Attributes["key"].Value;
                    string value = l.Attributes["value"].Value;
                    sectionNode.Add(name, value);
                }
            }
            return sectionNode;
        }
    }
}